package com.elite.groovy.callback

import java.security.MessageDigest
import java.text.SimpleDateFormat

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.elite.groovy.util.EliteBean
import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import net.sf.json.JSONArray
import net.sf.json.JSONObject

class OutBoundActivity implements ServiceBackInvoke{

	private static final Log log=LogFactory.getLog(OutBoundActivity.class);

	@Override
	public String doCallBack(EliteBean elite, HttpServletRequest request,HttpServletResponse response) {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
		
			JSONObject result = new JSONObject();
			//获取配置文件中配置好的企业号、代理ip及端口
			PropertiesUtil cfg = new PropertiesUtil();

			def enterpriseID = cfg.readValue("QingNiu.enterpriseID");

			String proxyIp = cfg.readValue("QingNiu.ProxyIP");

			int proxyPort=0;

			if(cfg.readValue("QingNiu.ProxyPort")!=null&&cfg.readValue("QingNiu.ProxyPort")!="") {

				proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
			}

			String getMethod = request.getMethod();

			log.debug("getMethod:" + getMethod);

			String inData = "";

			String outData = "";

			String Request_Type="";//返回类型

			String Response_Code="";//返回代码

			String Message="";//返回描述

			BufferedReader iny = null;
			
			Date date=new Date();
			
			//当前系统时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			
			//获得当前系统时间字符串
			String date2=sdf.format(date);
			
			def salt = "8127cc9b6adfd49946bf07140d301f6c";
			
			StringBuffer s = new StringBuffer();
			s.append(enterpriseID);
			s.append(date2);
			s.append(salt);
			
			String ss = s.toString();
			
			def tk = MD5(ss);

			if (getMethod.equals("GET")) {

				inData = request.getParameter("data");

				log.debug("原始Get请求参数:" + inData);

			} else {
				InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");

				iny = new BufferedReader(reader);

				String line;

				while ((line = iny.readLine()) != null) {

					inData += line;
				}

				log.debug("原始Post请求参数:" + inData);
			}

			JSONArray array = new JSONArray();
			
			JSONObject jsonObject1 = new JSONObject().fromObject(inData);
			
			//String eUrl = "http://localhost:8080/EliteGeneralHttpTask/api/";

			String requestId = GetJV(jsonObject1, "requestId")
			JSONObject timeRange = new JSONObject();

							String startTime = GetJV(jsonObject1, "startTime");

							String endTime = GetJV(jsonObject1, "endTime");

							timeRange.put("startTime", startTime);

							timeRange.put("endTime", endTime);
							
							JSONObject timeRange1 = new JSONObject();
							
							String startTime1 = GetJV(jsonObject1, "startTime1");
							
							String endTime1 = GetJV(jsonObject1, "endTime1");
							
							timeRange1.put("startTime", startTime1);
							
							timeRange1.put("endTime", endTime1);

							array.add(timeRange);
							
							if(!startTime1.equals("") && startTime1!="") {
								
								array.add(timeRange1);
							}
			
			log.debug(array);
			
			String caller = GetJV(jsonObject1, "caller");

			String callType = GetJV(jsonObject1, "callType");

			String repeatTimes = GetJV(jsonObject1, "repeatTimes");

			String processId = GetJV(jsonObject1, "processId");

			String spanSec = GetJV(jsonObject1, "spanSec");

			String businessSendcId = GetJV(jsonObject1, "businessSendcId");

			String token = tk.toUpperCase();

			JSONObject json = new JSONObject();

			json.put("enterpriseID", enterpriseID);

			json.put("requestId", requestId);

			json.put("timeRange",array);

			json.put("caller",caller);

			//json.put("callType",callType);

			json.put("repeatTimes",repeatTimes);

			json.put("processId",processId);

			json.put("spanSec",spanSec);

			json.put("businessSendcId",businessSendcId);

			//json.put("skillGroup",skillGroup);

			json.put("token",token);

			String qnUrl = "select webserviceurl from Sysc_Interface where webtype ='STATCALL'";
				def postURL=elite.chaxun_sql(qnUrl, "dataSource");
				def url=postURL[0].get("WEBSERVICEURL");
				
			def reJson = HttpClientProxy.sendPost(url, json.toString(),proxyIp,proxyPort);
			JSONObject jsons = new JSONObject().fromObject(reJson);
			String I_Sync_Type="ROBOT1";
			def insertSQL="DECLARE  clobValue qt_dm_ifc_log_new.Send_Info%TYPE; clobValue1 qt_dm_ifc_log_new.return_info%TYPE;  BEGIN  clobValue:='" + json.toString() + "' ; clobValue1:='" + reJson + "';insert into qt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'" + requestId + "','" + I_Sync_Type + "',clobValue,clobValue1,sysdate,sysdate);   COMMIT; END;";
			elite.update(insertSQL,'dataSource');
			if(jsons.code==-1) {
				result.put("msg","-1");
				result.put("data",json.toString());
			}else if(jsons.code==0) {
			String sql = "update ROBOT_STANDARD_RULE set IS_FLAG = 1，MODIFIEDDATE=sysdate where CUSTLIST_NAME='" + requestId + "' and TASK_STATUS = 2";
			elite.update(sql, "dataSource");
			result.put("msg","0");
			result.put("data",json.toString());
			}
			return result;

	}

	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {

						try {
							Rev_Value = String.valueOf(inJson.getBoolean(getKey));
						} catch (Exception e4) {
							Rev_Value = "";
						}
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}

	public static String getRandomString( int length){
		//定义一个字符串（A-Z，a-z，0-9）即62位；
		String str= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890" ;
		//由Random生成随机数
		Random random= new Random();
		StringBuffer sb= new StringBuffer();
		//长度为几就循环几次
		for ( int i= 0 ; i<length; ++i){
			//产生0-61的数字
			int number=random.nextInt( 25 );
			//将产生的数字通过length次承载到sb中
			sb.append(str.charAt(number));
		}
		//将承载的字符转换成字符串
		return sb.toString();
	}
	
	public static String getRandomNum( int length){
		String str= "123456789009876543210123456789" ;
		//由Random生成随机数
		Random random= new Random();
		StringBuffer sb= new StringBuffer();
		//长度为几就循环几次
		for ( int i= 0 ; i<length; ++i){
			//产生0-61的数字
			int number=random.nextInt( 25 );
			//将产生的数字通过length次承载到sb中
			sb.append(str.charAt(number));
		}
		//将承载的字符转换成字符串
		return sb.toString();
	}
	
	// MD5加码。32位
	public static String MD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];

		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();

		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}

		return hexValue.toString();
	}

	// 可逆的加密算法
	public static String KL(String inStr) {
		// String s = new String(inStr);
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;
	}

	// 加密后解密
	public static String JM(String inStr) {
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String k = new String(a);
		return k;
	}
}
